package com.chuangtie.secondary.lining.common.util.copy;


import com.chuangtie.secondary.lining.common.exception.OpenException;
import com.chuangtie.secondary.lining.common.response.OpenResponseCode;
import org.springframework.beans.BeanUtils;

import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * 对象拷贝工具类
 *
 *  @author : liaozhiwei
 *  @date : 23:25 2024/7/8
 */
public final class BeanCopyUtil {

    private BeanCopyUtil() {

    }

    public static <T> T copy(final Object source, final Class<T> clazz) {
        if (source == null) {
            return null;
        }
        try {
            T t = clazz.newInstance();
            BeanUtils.copyProperties(source, t);
            return t;
        } catch (InstantiationException e) {
            throw new OpenException(OpenResponseCode.BEAN_COPY_FAILED);
        } catch (IllegalAccessException e) {
            throw new OpenException(OpenResponseCode.BEAN_COPY_FAILED);
        }
    }

    public static <T> T copy(final Object source, final Class<T> clazz, String... ignoreProperties) {
        if (source == null) {
            return null;
        }
        try {
            T t = clazz.newInstance();
            BeanUtils.copyProperties(source, t, ignoreProperties);
            return t;
        } catch (InstantiationException e) {
            throw new OpenException(OpenResponseCode.BEAN_COPY_FAILED);
        } catch (IllegalAccessException e) {
            throw new OpenException(OpenResponseCode.BEAN_COPY_FAILED);
        }
    }

    public static <E, V> List<V> copyListToList(List<E> source, Class<V> clazz) {
        return source.stream().map(pojo -> copy(pojo, clazz)).collect(toList());
    }

    public static <E, V> List<V> copyListToList(List<E> source, Class<V> clazz, String... ignoreProperties) {
        return source.stream().map(pojo -> copy(pojo, clazz, ignoreProperties)).collect(toList());
    }
}
